import { computed, onBeforeMount, reactive } from "vue"
import { DEFAULT_PRIMARY } from '@/config/themeConfig'
import { ElMessage } from "element-plus";
import { getLightColor, getDarkColor } from '@/utils/tool'
import store from '@/store/index'


const body = document.documentElement

const themeConfig = computed(() => {
    return store.getters['theme/getThemeConfig']
})

export const useTheme = ()  => {
    // 切换暗黑模式
    const switchDark = () => {
        if (themeConfig.isDark) {
            body.setAttribute('class', 'dark')
        } else {
            body.setAttribute('class', '')
        }
    }

    // 修改主题颜色
    const changePrimaryColor = (val) => {
        if (!val) {
            val = DEFAULT_PRIMARY
            ElMessage.success(`主题颜色已重置为 ${DEFAULT_PRIMARY}`)
        }
        store.commit('theme/setThemeConfig', {...themeConfig.value, primary: val})
        // 颜色加深
		document.documentElement.style.setProperty("--el-color-primary-dark-2", `${getDarkColor(themeConfig.value.primary, 0.1)}`);
		document.documentElement.style.setProperty("--el-color-primary", themeConfig.value.primary);
		// 颜色变浅
		for (let i = 1; i <= 9; i++) {
			document.documentElement.style.setProperty(
				`--el-color-primary-light-${i}`,
				`${getLightColor(themeConfig.value.primary, i / 10)}`
			);
		}
    }

    // 灰色/ 弱色 切换
    const changeGreyOrWeak = (value, type) => {
        if (!value) return body.setAttribute('style', '')
        if (type === 'grey') body.setAttribute('style', 'filter: grayscale(1)')
        if (type === 'weak') body.setAttribute('style', 'filter: invert(80%)')
        let propName = type === 'grey' ? 'isWeak': 'isGrey'
        store.commit('theme/setThemeConfig', {...themeConfig.value, [propName]: false})
    }

    onBeforeMount(() => {
        switchDark()
        changePrimaryColor(themeConfig.value.primary)
        if (themeConfig.value.isGrey) changeGreyOrWeak(true, "grey");
		if (themeConfig.value.isWeak) changeGreyOrWeak(true, "weak");
    })

    return {
		switchDark,
		changePrimaryColor,
		changeGreyOrWeak
	};
}